package com.jn.okhttp.views;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jn.okhttp.R;
import com.jn.okhttp.adapter.HotSearchAdapter;
import com.jn.okhttp.entity.HotSearchItem;

import java.util.ArrayList;
import java.util.List;

public class ResultActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private HotSearchAdapter adapter;
    private List<HotSearchItem> hotSearchItems;
    private Button backButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        recyclerView = findViewById(R.id.recycler_view);
        backButton = findViewById(R.id.button_back);

        hotSearchItems = new ArrayList<>();
        adapter = new HotSearchAdapter(hotSearchItems, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        String responseData = getIntent().getStringExtra("responseData");
        if (responseData != null) {
            parseHotSearchJson(responseData);
        } else {
            Toast.makeText(this, "未获取到数据", Toast.LENGTH_LONG).show();
        }

        backButton.setOnClickListener(view -> finish());
    }

    private void parseHotSearchJson(String jsonData) {
        Gson gson = new Gson();
        JsonObject jsonObject = JsonParser.parseString(jsonData).getAsJsonObject();

        if (jsonObject.has("result") && !jsonObject.get("result").isJsonNull()) {
            hotSearchItems.clear(); // 清除旧数据
            JsonArray results = jsonObject.getAsJsonArray("result");
            for (int i = 0; i < results.size(); i++) {
                JsonObject item = results.get(i).getAsJsonObject();
                String title = item.get("title").getAsString();
                String hotValue = item.get("hotValue").getAsString();
                String link = item.get("link").getAsString();
                hotSearchItems.add(new HotSearchItem(title, hotValue, link));
            }
            adapter.notifyDataSetChanged(); // 通知数据已更新
        } else {
            Toast.makeText(this, "未获取到有效的结果数据", Toast.LENGTH_LONG).show();
        }
    }
}
